package ar.com.solidussource.howmuchservices.web.controller.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import ar.com.solidussource.howmuchservices.common.entities.User;

public class UserValidationInterceptor extends HandlerInterceptorAdapter {
	private static final Logger log = Logger.getLogger(UserValidationInterceptor.class);
	private static String CURRENT_USER = "currentUser";
	private static String USER_IS_NOT_LOGGED = "user is not logged";
	private static String JSON_USER_IS_NOT_LOGGED = "{\"status\":\""+USER_IS_NOT_LOGGED+"\"}";
	private static String[] EXCLUDED_ACTIONS = {"login.json", "register.json", "passwordrecovery.json"};
	private static String JSON_CONTENT_TYPE = "application/json";
		
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
/*		if (!isThereAnyExclusion(request.getRequestURI())) {
			if (isUserLogged(request.getSession())) {
				return true;
			} else {
				log.error(USER_IS_NOT_LOGGED);
				response.setContentType(JSON_CONTENT_TYPE);
				response.getWriter().write(JSON_USER_IS_NOT_LOGGED);
				return false;
			}			
		}*/
		
		return true;
		
	}
	
	private boolean isUserLogged(HttpSession session){		
		User user = (User) session.getAttribute(CURRENT_USER);
		if (user != null) {
			if (user.getUsername() != null || !user.getUsername().equals("")) {
				return true;
			} else {
				return false;
			}
			
		} else {
			return false;
		}
	}
	
	private boolean isThereAnyExclusion(String requestURI){
		int i = 0;
		
		while (i < EXCLUDED_ACTIONS.length) {
			if (requestURI.contains(EXCLUDED_ACTIONS[i])) {
				return true;
			}
			i++;
		}
		
		return false;
	}

}
